package oop.ex2.filters;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.*;
import oop.ex2.filters.exceptions.*;

/**
 * Filters of a date comparison type. 
 */
class CompareDateFilter extends ComparableFilter<Date> {
	//********************************************************************
	//  Finals :                                                         *
	//********************************************************************
	private static final String DATE_FORMAT = "dd/MM/yyyy";
	//********************************************************************
	//  Data members :                                                   *
	//********************************************************************
	private SimpleDateFormat _dateFormat;
	private Date _date;
	//********************************************************************
	//  Methods :                                                        *
	//********************************************************************
	/**
	 * Construct a new date filter.
	 * @param compareMode Compare mode.
	 */
	public CompareDateFilter(int compareMode ){
		super(compareMode);
		_dateFormat = new SimpleDateFormat(DATE_FORMAT);
		_dateFormat.setLenient(false);
    }
	/**
	 * Returns file's last modification date - rounded to day-precision.
	 * @return File's last modification date.
	 */
	public Date getFileData(){
		return getRoundDate(new Date(_file.lastModified()));
	}
	/**
	 * Rounds the date to be precise by the day from a miliSec precision. 
	 * @param miliSecDate Date represented as number of miliSecs past
	 * since 1970. 
	 * @return The date rounded to a day precision.
	 */
	private Date getRoundDate(Date miliSecDate){
		GregorianCalendar greg = new GregorianCalendar();
		greg.setTime(miliSecDate);
		
		//Set the time to 00:00 so as to ignore time differences within
		//a day.
		greg.set(GregorianCalendar.HOUR, 0);
		greg.set(GregorianCalendar.MINUTE, 0);
		greg.set(GregorianCalendar.SECOND, 0);
		greg.set(GregorianCalendar.AM_PM, GregorianCalendar.AM);
		greg.set(GregorianCalendar.MILLISECOND, 0);
		return greg.getTime();
	}
	/**
	 * Returns the date to be compared.
	 * @return the date to be compared.
	 */
	public Date getComparableData(){
	    return _date;
	}
	/**
	 * Sets the data of the filter.
	 * @param data The data to be set.
	 * @throws FilterDataException in case of error in filter's data. 
	 */
	public void setData( String data ) throws FilterDataException {
	       try{
	            _date = _dateFormat.parse(data);
	        }
	        catch( ParseException e) {
	            throw new FilterDataException(
	                    "Error:Invalid filter parameters");
	        }
	}
	/**
	 *  Clones the object - return a new object with same properties.
	 *  @return A new copy of the filter.
	 */
	public Filter clone() {
	    return new CompareDateFilter(_compareMode );
	}
}
